package com.woniuxy.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Map;

public class UserContext {
    public static Integer getUserId() throws ParseException { //工具类, 用于获取JWT中的用户名
        //ServletRequestAttributes是tomcat帮我们封装的请求上下文类
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        String jwt = request.getHeader("authorization");
        Map userInfo = JWTUtil.getJWTUserInfo(jwt);
        return ((Long) userInfo.get("id")).intValue();
    }
}
